package com.adams.action.config;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import com.adams.common.BaseAction;
import com.adams.common.ConfigVO;
import com.adams.util.config.ConfigUtil;

/**
 * File Name : ConfigAction.java
 * 
 * @Description : 配置jdbc.properties sysconfig.properties文件
 * @author 904941
 */
public class ConfigAction extends BaseAction
{

	/**
	 * Description : 保存参数到配置文件中（jdbc.properties,sysconfig.properties）
	 * 
	 * @return String 结果页面
	 * @author 904941
	 * 
	 */
	public String saveConfig()
	{
		if (validateField(request))
		{
			saveConfig(request);// 保存文件
			request.setAttribute("configed", "configed");// 表示已经配置
		}

		return SUCCESS;// 返回页面
	}

	// 保存到（jdbc.properties,config/sysconfig.properties）properties文件中
	private void saveConfig(HttpServletRequest request)
	{
		saveJdbcProperties();
		saveSysProperties();
	}

	// 必输栏位验证
	private boolean validateField(HttpServletRequest request)
	{
		ConfigVO configVO = new ConfigVO();
		Map parameterMap = request.getParameterMap();
		Object[] enumsJdbc = configVO.getAdamsJdbcMap().keySet().toArray();
		Object[] enumsSys = configVO.getAdamsSysMap().keySet().toArray();
		for (int i = 0; i < enumsJdbc.length; ++i)
		{
			String key = (String) enumsJdbc[i];
			if (parameterMap.containsKey(key)
					&& "".equals(request.getParameter(key) == null ? ""
							: request.getParameter(key).toString().trim()))
			{
				request.setAttribute("msg", ((String) configVO
						.getAdamsJdbcMap().get(key))
						+ "不能为空");
				return false;
			}
		}
		for (int i = 0; i < enumsSys.length; ++i)
		{
			String key = (String) enumsSys[i];
			if (parameterMap.containsKey(key)
					&& "".equals(request.getParameter(key) == null ? ""
							: request.getParameter(key).toString().trim()))
			{
				request.setAttribute("msg", ((String) configVO.getAdamsSysMap()
						.get(key))
						+ "不能为空");
				return false;
			}
		}

		return true;
	}

	// 保存到jdbc.properties文件中
	private void saveJdbcProperties()
	{
		// 文件名
		String jdbcPropertiesFileName = "jdbc.properties";
		// 完整文件路径
		String jdbcProperitiesDir = ConfigAction.class.getClassLoader()
				.getResource("").getPath()
				+ File.separator + jdbcPropertiesFileName;

		// 见一个properties文件主要是获取其值比较方便 有些字段部分修改 如：数据库URL
		Properties jdbcProperties = new Properties();
		// Properties文件从该流获取内容
		jdbcProperties = ConfigUtil.loadProperties(jdbcPropertiesFileName,
				jdbcProperitiesDir);
		StringBuilder sbContent = new StringBuilder();

		BufferedReader br = null;
		ConfigVO configVO = new ConfigVO();
		try
		{
			// 一行行的读取 碰到需要修改的字段就修改成页面设置的值
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					jdbcProperitiesDir), "UTF-8"));
			if (br != null)
			{
				String strLine;
				Object[] enumsJdbc = configVO.getAdamsJdbcMap().keySet()
						.toArray();

				boolean bExist = false;
				while ((strLine = br.readLine()) != null)
				{
					if (!strLine.startsWith("#"))
					{
						for (int i = 0; i < enumsJdbc.length; i++)
						{
							String key = (String) enumsJdbc[i];
							if (strLine.indexOf(key) > -1)
							{
								if (ConfigVO.JDBC_URL_NAME.equals(key))
								{
									String value = jdbcProperties
											.getProperty(key);
									sbContent.append(key
											+ "="
											+ value.substring(0, value
													.indexOf("//") > -1 ? value
													.indexOf("//") + 2 : 0)
											+ new String(request.getParameter(
													key).getBytes("GBK"),
													"UTF-8")
											+ value.substring(value
													.indexOf("?") > -1 ? value
													.indexOf("?") : value
													.length()));
								} else
									sbContent.append(key
											+ "="
											+ new String(request.getParameter(
													key).getBytes("GBK"),
													"UTF-8"));

								bExist = true;
								break;
							}
						}
						if (!bExist)
						{// 不是需要设置的字段就直接读取该行内容
							sbContent.append(strLine);
						}
					} else
					{
						sbContent.append(strLine);
					}

					sbContent.append("\r\n");
					bExist = false;

				}
			}
		} catch (IOException e)
		{
			e.printStackTrace();
			throw new RuntimeException("loading" + jdbcPropertiesFileName
					+ " file error");
		} finally
		{
			if (br != null)
				try
				{
					br.close();// 关闭读文件的流
				} catch (IOException e)
				{
					throw new RuntimeException(
							"close BufferedReader Stream error");
				}
		}

		writeStringToPropertyFile(jdbcPropertiesFileName, jdbcProperitiesDir,
				"UTF-8", sbContent.toString());
	}

	// 保存到sysconfig.properties文件中
	private void saveSysProperties()
	{
		// 文件名
		String sysPropertiesFileName = System.getProperty("os.name").toString()
				.startsWith("Windows") ? "win-sysconfig.properties"
				: "linux-sysconfig.properties";
		// 完整文件路径
		String sysProperitiesDir = ConfigAction.class.getClassLoader()
				.getResource("").getPath()
				+ File.separator
				+ "config"
				+ File.separator
				+ sysPropertiesFileName;

		// 见一个properties文件主要是获取其值比较方便 有些字段部分修改 如：数据库URL
		Properties sysProperties = new Properties();
		// Properties文件从该流获取内容
		sysProperties = ConfigUtil.loadProperties(sysPropertiesFileName,
				sysProperitiesDir);

		StringBuilder sbContent = new StringBuilder();

		BufferedReader br = null;
		ConfigVO configVO = new ConfigVO();
		try
		{
			// 一行行的读取 碰到需要修改的字段就修改成页面设置的值
			br = new BufferedReader(new InputStreamReader(new FileInputStream(
					sysProperitiesDir), "UTF-8"));
			if (br != null)
			{
				String strLine;
				Object[] enumsSys = configVO.getAdamsSysMap().keySet()
						.toArray();
				boolean bExist = false;
				while ((strLine = br.readLine()) != null)
				{
					if (!strLine.startsWith("#"))
					{
						for (int i = 0; i < enumsSys.length; i++)
						{
							String key = (String) enumsSys[i];
							if (strLine.indexOf(key) > -1)
							{
								sbContent.append(key
										+ "="
										+ new String(request.getParameter(key)
												.getBytes("GBK"), "UTF-8"));
								bExist = true;
								break;
							}
						}
						if (!bExist)
						{// 不是需要设置的字段就直接读取该行内容
							sbContent.append(strLine);
						}
					} else
					{
						sbContent.append(strLine);
					}

					sbContent.append("\r\n");
					bExist = false;

				}
			}
		} catch (IOException e)
		{
			e.printStackTrace();
			throw new RuntimeException("loading" + sysPropertiesFileName
					+ " file error");
		} finally
		{
			if (br != null)
				try
				{
					br.close();// 关闭读文件的流
				} catch (IOException e)
				{
					throw new RuntimeException("close " + sysPropertiesFileName
							+ " BufferedReader Stream error");
				}
		}
		writeStringToPropertyFile(sysPropertiesFileName, sysProperitiesDir,
				"UTF-8", sbContent.toString());

	}

	/**
	 * Description 写文件
	 * 
	 * @param fileName
	 *            文件的名字
	 * @param fileDir
	 *            文件的全路径
	 * @author 904941
	 */
	private void writeStringToPropertyFile(String fileName, String fileDir,
			String charset, String strContent)
	{
		PrintWriter pw = null;
		try
		{
			pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(
					fileDir), charset));
			if (pw != null)
			{
				pw.print(strContent);// 将内容写到文件中
			}
			pw.flush();// 刷新文件
		} catch (IOException e)
		{
			e.printStackTrace();
			throw new RuntimeException("writing " + fileName + " file error");
		} finally
		{
			if (pw != null)
			{
				pw.close();
			}
		}
	}

	public static String getAbsApplicationPath()
	{
		String path = ConfigAction.class.getClassLoader().getResource("")
				.getPath();
		try
		{
			path = URLDecoder.decode(path, "utf-8");
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		path = path
				.replaceAll("/", "\\" + System.getProperty("file.separator"));
		if (System.getProperty("file.separator").equals("\\"))// windows
			path = path.substring(1);

		return path;
	}

}
